class CurrencyExchangeRateController < ApplicationController
  before_filter :authenticate_user!

  def rates
    columns = params[:currencies] && params[:currencies].split(",") || current_user.currencies_codes
    if not columns.kind_of? Array
      renderError(5101)
    end
    columns.push("timestamp")

    begin
      @rates = CurrencyExchangeRate.select(columns.map {|c| "currency_exchange_rates.\"#{c}\""}).where(getTimeCondition(params))
      render :json => @rates.as_json
    rescue
      columns.delete("timestamp")
      renderError(5102, columns.join(", "))
    end
  end

  private
    def getTimeCondition params
      from, to = params[:from], params[:to]
      if !from.nil? && !to.nil?
        ["timestamp >= :from AND timestamp <= :to", {:from => from, :to => to}]
      elsif !from.nil?
        ["timestamp >= :from", {:from => from}]
      elsif !to.nil?
        ["timestamp <= :to", {:from => from, :to => to}]
      else
        []
      end
    end



end
